//
//  NXAppUpdate.m
//  NXLib
//
//  Created by AK on 14-2-19.
//  Copyright (c) 2014年 AK. All rights reserved.
//

#import "NXAppUpdate.h"
#import "CJSONDeserializer.h"

#define aaaa @"aaaa"

//#define bbbb [@"cccc" stringByAppendingString:aaaa]

#define bbbb [NSString stringWithFormat:@"aaaa%@",@"ccccc"]

@interface NXAppUpdate()
{

    NSString * currentVersion;
    
  
}
@end

@implementation NXAppUpdate

- (id)init
{

    if (self = [super init])
    {
        NSDictionary * infoDic = [[NSBundle mainBundle] infoDictionary];
        CFShow((__bridge CFTypeRef)(infoDic));
        currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
        NSLog(@"now version is %@",currentVersion);
        
        
        
        NSLog(@"asdfsdaf %@",bbbb);
    }
    return self;
}

- (NSString *)checkAppUpateWithAppID:(NSString *)appID
{
    NSString * URL = [NSString stringWithFormat:@"%@%@",@"http://itunes.apple.com/lookup?id=",appID];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:URL]];
    [request setHTTPMethod:@"POST"];
    NSHTTPURLResponse * urlResponse = nil;
    NSError * error = nil;
    NSData * recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    
    NSDictionary * dic = [[CJSONDeserializer deserializer] deserialize:recervedData error:&error];;
    NSArray * infoArray = [dic objectForKey:@"results"];
    if ([infoArray count])
    {
        NSDictionary * releaseInfo = [infoArray objectAtIndex:0];
        NSString * lastVersion = [releaseInfo objectForKey:@"version"];
        NSLog(@"appstore new version is %@",lastVersion);
        
        //有的办法是判断string isEqualToString 方法 这个方法不好，要用INT 苹果后台新上传的可以是小于上线版本
        lastVersion = [lastVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
        
        currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];

        if (lastVersion.intValue > currentVersion.intValue)
        {
            return [releaseInfo objectForKey:@"trackViewUrl"];
        }
        else
        {
        
            return nil;
        }
    }
    else
    {
        return nil;
    }

}

@end
